/**
 * Created by wtfssd on 2017/9/15.
 */

import React, {Component} from 'react'
import {
    StyleSheet, Text, TextInput, View, AsyncStorage, Image, TouchableOpacity, ImageBackground, ScrollView
} from 'react-native'
import {connect} from 'react-redux'
import {List, Picker, TextareaItem, InputItem, Button} from 'antd-mobile'
import {Actions, ActionConst} from 'react-native-router-flux'
import propTypes from 'prop-types'
import NavigationBar from 'react-native-navbar'
import CommonStyle, {Color, size} from '../../assets/styles/index'
import {Line, MyIcon, BackButton} from '../common/index'
import districtData from '../../assets/json/province.json'
import {createForm} from 'rc-form';
import {toastValidateError} from '../../utils/tools'
import {phoneReg} from '../../utils/Reg'


import * as request from '../../utils/request'

class Page extends Component {
    constructor(props) {
        super(props);
        this.state = {
            district: [],
            address: ''
        };
    }

    /*组件将要加载*/
    componentWillMount() {

    }

    /*组件已经加载*/
    componentDidMount() {
        this.setState({district: districtData.map(({region}, index) => ({...region}))})
    }

    /*组件将要卸载*/
    componentWillUnmount() {

    }

    onSave() {
        const {form, dispatch, auth} = this.props;
        form.validateFields({force: true}, (error) => {
            if (!error) {
                let payload = form.getFieldsValue();
                payload.telphone = payload.telphone.replace(/ /g, '');
                payload.address = this.refs.address.props.extra;
                payload.user_id = auth.profile.member_id;
                let type = 'auth/addAddress';


                const fullAddress = `${payload.address}${payload.address_detail}`;
                request.getPromise(request.API.aMapGeo, {
                    key: request.API.aMapKey,
                    address: fullAddress,
                }).then((data) => {
                    if (Number(data.status) === 1) {
                        if (Array.isArray(data.geocodes) && data.geocodes.length > 0) {
                            const geo = data.geocodes[0];
                            const location = geo.location.split(',');
                            payload.lng = location[0];
                            payload.lat = location[1];
                            if (this.props.editType !== 'add') {
                                payload.id = this.props.address.id;
                            }
                            dispatch({
                                type,
                                payload
                            });
                            Actions.pop();
                        }
                    }
                }).catch((error) => {
                    console.log(error);
                });


            } else {
                toastValidateError(error);
            }
        });

    }

    render() {
        const {getFieldProps} = this.props.form;
        return (
            <View style={Styles.container}>
                <NavigationBar tintColor={Color.primary}
                               statusBar={{style: 'light-content'}}
                               title={{title: this.props.title, tintColor: 'white'}}
                               leftButton={<BackButton/>}

                />
                <ScrollView>
                    <List>
                        <InputItem  {...getFieldProps('accepter', {
                            initialValue: this.props.address.accepter,
                            rules: [
                                {required: true, message: '收货人未填写'},
                            ]
                        })}
                                    placeholder="输入收货人姓名"
                                    labelNumber={4}
                                    clear
                        >
                            收货人
                        </InputItem>

                        <InputItem  {...getFieldProps('telphone', {
                            initialValue: this.props.address.telphone,
                            rules: [
                                {required: true, message: '收货人联系电话未填写'},
                            ]
                        })}
                                    placeholder="输入联系电话"
                                    labelNumber={4}
                                    type="phone"
                                    clear
                        >
                            联系电话
                        </InputItem>

                        <Picker
                            title='请选择地区'
                            data={this.state.district}
                            format={(value) => value.join('')}
                            extra="请选择地区"
                            {...getFieldProps('address', {
                                rules: [
                                    {required: true, message: '收货地址未填写'},
                                ]
                            })}
                        >
                            <List.Item arrow="horizontal" ref='address'>选择地区</List.Item>
                        </Picker>
                        <InputItem  {...getFieldProps('address_detail', {
                            initialValue: this.props.address.address_detail,
                            rules: [
                                {required: true, message: '收货人详细地址未填写'},
                            ]
                        })}
                                    placeholder="输入详细地址"
                                    labelNumber={4}
                                    clear
                        >
                            详细地址
                        </InputItem>


                    </List>
                    <View style={[{marginTop: size(30)}, CommonStyle.centerVH]}>
                        <Button style={Styles.submit}
                                activeStyle={[Styles.submit, {opacity: 0.8}]}
                                loading={this.props.auth.loading}
                                disabled={this.props.auth.loading}
                                onClick={this.onSave.bind(this)}
                        >
                            <Text style={{color: 'white', fontSize: 14}}>保存</Text>
                        </Button>
                    </View>
                </ScrollView>

            </View>
        )
    }
}

const Styles = StyleSheet.create({
    container: {
        display: 'flex',
        flex: 1,
    },
    input: {
        padding: 12,
        fontSize: 16
    },
    submit: {
        width: size(180),
        height: size(33),
        backgroundColor: Color.primary,
        borderColor: Color.primary
    }
});

const addressProps = {
    accepter: propTypes.string,
    telphone: propTypes.string,
    address: propTypes.string,
    address_detail: propTypes.string,
};
Page.propTypes = {
    editType: propTypes.oneOf(['add', 'edit']),
    address: propTypes.shape(addressProps)
};
Page.defaultProps = {
    editType: 'add',
    address: {
        accepter: null,
        telphone: null,
        address: null,
        address_detail: null,
    }

}
const Wrapper = createForm()(Page);
export default connect(
    ({auth}) => ({auth})
)(Wrapper)





